<template>
  <Dialog
    class="edit-dialog"
    title="修改密码"
    :visible.sync="dialogVisible"
    @submit="submit"
  >
    <el-form ref="form" :rules="rules" :model="form" label-width="100px">
      <el-form-item label="密码" prop="pwd">
        <el-input
          type="password"
          v-model="form.pwd"
          autocomplete="off"
        ></el-input>
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPwd">
        <el-input
          type="password"
          autocomplete="off"
          v-model="form.checkPwd"
        ></el-input>
      </el-form-item>
    </el-form>
  </Dialog>
</template>

<script>
import { updatePasswordByAdmin } from "@/api";

export default {
  name: "UpdatePassword",
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    roleInfo: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      //对话框状态--------------------------------------------
      dialogVisible: this.visible,
      //表单信息--------------------------------------------
      form: {
        pwd: "",
        checkPwd: ""
      },
      //校验--------------------------------------------
      rules: {
        pwd: [
          { required: true, validator: this.validatePass, trigger: "blur" }
        ],
        checkPwd: [
          { required: true, validator: this.validatePass2, trigger: "blur" }
        ]
      }
    };
  },

  watch: {
    //监听对话框状态--------------------------------------------
    dialogVisible(newVal) {
      this.$emit("update:visible", newVal);
    }
  },

  methods: {
    //校验密码--------------------------------------------
    validatePass(rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.form.pwd !== "") {
          this.$refs.form.validateField("checkPwd");
        }
        callback();
      }
    },
    //校验密码--------------------------------------------
    validatePass2(rule, value, callback) {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.form.pwd) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    },

    //校验结果--------------------------------------------
    validate() {
      let flag;
      this.$refs.form.validate(valid => {
        flag = valid;
      });
      return flag;
    },

    //确定提交--------------------------------------------
    submit() {
      if (!this.validate()) return;
      const data = {
        password: this.form.pwd,
        uuid: this.roleInfo.uuid
      };
      updatePasswordByAdmin(data).then(res => {
        if ((res.state = 100)) {
          this.$message({ message: res.msg, type: "success" });
          this.dialogVisible = false;
        }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.el-tree {
  min-height: 300px;
  max-height: 500px;
}
</style>
